<template>
  <PageWrapper dense contentBackground>
    <BasicForm @register="registerForm">
      <template #businessTime>
        <div class="weeks-box">
          <div v-for="(item, index) in businessList" :key="index" class="weeks-box-one">
            <div class="business-box-item">
              <div class="weeks-item">
                {{ item.day }}
                <!-- <Select v-model:value="item.startWeeks"
                        :allowClear="true"
                        :options="weeksOptions" />
                <span>-</span>
                <Select v-model:value="item.endWeeks"
                        :allowClear="true"
                        :options="weeksOptions" /> -->
                <a-button @click="addBusinessTime(index)" type="primary">添加时间</a-button>
              </div>
              <div class="time-item">
                <div v-for="(ele, i) in item.children" :key="i">
                  <TimePicker v-model:value="ele.startTime" format="HH:mm" />
                  <span>-</span>
                  <TimePicker v-model:value="ele.endTime" format="HH:mm" />
                  <a-button @click="deleteTime(index, i)" type="danger">删除时间</a-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #citySelect="{ model, field }">
        <Select
          v-model:value="model[field]"
          show-search
          :allowClear="true"
          :filter-option="false"
          @change="cityChange"
          :options="cityOptions"
        />
      </template>
      <template #areaSelect="{ model, field }">
        <Select
          v-model:value="model[field]"
          show-search
          :allowClear="true"
          :filter-option="false"
          :options="areaOptions"
        />
      </template>
      <template #areaSearchInput="{ model, field }">
        <!-- <Select v-model:value="model[field]"
                show-search
                :allowClear="true"
                :filter-option="false"
                @search="search"
                @change="addressChange"
                :options="addressOptions" /> -->
        <!-- <AutoComplete v-model:value="model[field]"
                      :data-source="addressOptions"
                      placeholder="Email"
                      @search="search"
                      @change="search" /> -->
        <div class="address-list">
          <Input
            v-model:value="model[field]"
            :allowClear="true"
            @blur="areaSearchBlur"
            class="address-item"
            @change="search"
          />
          <ul>
            <li
              v-for="item in addressOptions"
              :key="item.value"
              class="address-item"
              @click="addressChange(item.value)"
            >
              {{ item.label }}
            </li>
          </ul>
        </div>
      </template>
      <template #areaSearch="{ model, field }">
        <ApiSelect
          :api="ListApi"
          class="selext"
          showSearch
          v-model:value="model[field]"
          optionFilterProp="label"
          resultField="list"
          labelField="name"
          valueField="id"
        />
      </template>
      <template #coverUrlSlot="{ model, field }">
        <Spin :spinning="spinning">
          <Upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            :show-upload-list="false"
            :action="uploadImgApi"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="model[field]" :src="model[field]" alt="avatar" />
            <div v-else>
              <div class="ant-upload-text">点击上传</div>
            </div>
          </Upload>
        </Spin>
        <div class="hint">建议图片尺寸：宽750*高440rpx</div>
      </template>
    </BasicForm>
    <Row>
      <Col :span="5" />
      <Col :span="12">
        <Button type="primary" @click="sub" style="margin-right: 15px">保存</Button>
        <Button @click="goBack">返回</Button>
      </Col>
    </Row>
  </PageWrapper>
</template>

<script lang="ts">
  import { PageWrapper } from '/@/components/Page';
  import { defineComponent, ref, toRefs, unref, onMounted } from 'vue';
  import { BasicForm, ApiSelect, useForm } from '/@/components/Form/index';
  import {
    Input,
    Select,
    TimePicker,
    Upload,
    Button,
    Row,
    Col,
    Spin,
    AutoComplete,
  } from 'ant-design-vue';
  import { ListApi } from '/@/api/merchant/index';
  import {
    weeksOptions,
    Ioptions,
    schemas,
    IbusinessTime,
    FileItem,
    FileInfo,
    times,
    Time,
    ChildrenTime,
  } from './data';
  import moment from 'moment';
  import { SearchByKeyWordsApi, getAreaSiteApi } from '/@/api/common/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { AddApi, getInfoApi, EditApi } from '/@/api/merchant/index';
  import { useRouter } from 'vue-router';
  import { debounce } from 'lodash-es';
  import { throttle } from '/@/utils/throttle';
  import { GetcitylistApi, getfindCityAreaSchools } from '/@/api/activityAdmin/index';
  import { getAppEnvConfig } from '/@/utils/env';
  import { cloneDeep } from 'lodash-es';
  export default defineComponent({
    name: 'AddForm',
    components: {
      BasicForm,
      PageWrapper,
      Input,
      Select,
      ApiSelect,
      TimePicker,
      Upload,
      Button,
      Row,
      Col,
      Spin,
      AutoComplete,
    },
    props: {
      id: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      getCity();
      const { id } = toRefs(props);
      const router = useRouter();
      const { createMessage } = useMessage();
      const cityName = ref<String>('');
      const addressClass = ref<String>('');
      // const cityId = ref<String | Number>('');
      // 详情地址选择框
      const addressOptions = ref<Ioptions[]>([]);
      // 市区选择框
      const cityOptions = ref<Ioptions[]>([]);
      // 区域选择框
      const areaOptions = ref<Ioptions[]>([]);
      const businessList = ref<Time[]>(cloneDeep(times));
      // 图片APi
      const uploadImgApi = ref<string>(getAppEnvConfig().VITE_GLOB_API_URL + '/mini/getFileUrl');
      const spinning = ref<boolean>(false);
      const fileList = ref([]);
      const [registerForm, { setFieldsValue, validate, resetFields, getFieldsValue }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        wrapperCol: { xxl: 9, xl: 12, md: 24 },
        // baseColProps: { span: 24 },
        actionColOptions: { xxl: 9, xl: 12, md: 24 },
      });
      businessList.value = cloneDeep(times);
      if (unref(id)) {
        editData(unref(id));
      }
      function editData(id: any) {
        getInfoApi(id).then((res) => {
          if (res.code == 200) {
            const { data } = res;
            const keys: string[] = [
              'id',
              'shopName',
              'phone',
              'doBusinessTime',
              'type',
              'address',
              'city',
              'coverUrl',
              'area',
              // 'discount',
              // 'discountRate',
              'qualification',
              'activityDescribe',
              'remark',
              'imgUrlsList',
              'videoUrlsList',
              'province',
              'discountInformation',
            ];
            const obj = {};
            for (const key of keys) {
              if (key == 'discount' || key == 'qualification') {
                obj[key] = data[key] || data[key] == 0 ? data[key] + '' : '';
              } else if (key == 'city') {
                // addressSearch(data[key]);
                // addressChange(data[key]);
                cityChange(data[key]);
                obj[key] = data[key];
              } else if (key == 'discountRate') {
                obj[key] = data[key] || '';
              } else if (key == 'videoUrlsList' || key == 'imgUrlsList') {
                obj[key] = data[key] ? data[key] : [];
              } else if (key == 'doBusinessTime') {
                // let times: string[] = data[key].split(',');
                // times.map((item: string, index: number) => {
                //   const obj: any = {
                //     startWeeks: item.slice(0, 2),
                //     endWeeks: item.slice(3, 5),
                //     startTime: moment(item.slice(6, 11), 'HH:mm'),
                //     endTime: moment(item.slice(12, 17), 'HH:mm'),
                //   };
                //   if (index == 0) {
                //     businessList.value[0] = obj;
                //   } else {
                //     businessList.value.push(obj);
                //   }
                // });
                if (data[key].indexOf('{') != -1) {
                  formaTime(data[key]);
                  obj[key] = data[key];
                }
              } else {
                obj[key] = data[key];
              }
            }
            if (obj['city']) {
              setTimeout(() => {
                setCityName(obj['city']);
              }, 1000);
              // cityId.value = obj['city'];
            }
            setFieldsValue(obj);
          }
        });
      }
      function formaTime(value) {
        const timeArr = JSON.parse(value);
        businessList.value.map((item) => {
          timeArr.map((element) => {
            if (item.day === element.day) {
              item.children = element.children;
            }
          });
        });
        businessList.value.forEach((item) => {
          if (item.children) {
            item.children.forEach((element) => {
              element.startTime = moment(element.startTime, 'HH:mm');
              element.endTime = moment(element.endTime, 'HH:mm');
            });
          }
        });
      }
      // 添加营业时间
      function addBusinessTime(i: number) {
        // businessList.value.push({
        //   startWeeks: '',
        //   endWeeks: '',
        //   startTime: moment('00:00', 'HH:mm'),
        //   endTime: moment('00:00', 'HH:mm'),
        // });
        if (businessList.value[i].children) {
          businessList.value[i].children?.push({
            startTime: moment('00:00', 'HH:mm'),
            endTime: moment('00:00', 'HH:mm'),
          });
        } else {
          businessList.value[i].children = [
            {
              startTime: moment('00:00', 'HH:mm'),
              endTime: moment('00:00', 'HH:mm'),
            },
          ];
        }
      }
      function deleteTime(index: number, i: number) {
        businessList.value[index].children?.splice(i, 1);
      }
      // 详情地址
      function addressSearch(record: any) {
        addressOptions.value = [];
        if (record) {
          SearchByKeyWordsApi({ keyword: record, cityName: cityName.value }).then((res) => {
            res.data.map((items) => {
              let item = {
                key: items.address,
                label: items.address,
                value: items.address,
              };
              addressOptions.value.push(item);
              // dataSource.value.push(item.value);
              // console.log(dataSource.value);
            });
          });
        }
      }
      function areaSearchBlur() {
        if (addressClass.value != 'address-item') {
          setTimeout(() => {
            addressOptions.value = [];
          }, 200);
        }
      }
      onMounted(() => {
        document.addEventListener('click', dc);
      });
      const dc = (e: MouseEvent) => {
        addressClass.value = e.target.getAttribute('class');
      };
      // 获取城市
      function getCity() {
        GetcitylistApi().then((res) => {
          res.data.map((items) => {
            const item: Ioptions = {
              key: items.id,
              label: items.city,
              value: items.id,
            };
            item.value = items.id.toString();
            cityOptions.value.push(item);
          });
        });
      }
      function cityChange(e: string) {
        setCityName(e);
        setFieldsValue({ area: '' });
        areaOptions.value = [];
        const el = parseInt(e);
        getfindCityAreaSchools(el).then((res) => {
          res.data.area.map((items) => {
            let item = {
              key: items,
              label: items,
              value: items,
            };
            areaOptions.value.push(item);
          });
        });
      }
      function setCityName(e: string) {
        const item = cityOptions.value.filter((item: Ioptions) => {
          return item.value == e;
        });
        if (item.length > 0) {
          cityName.value = item[0].label;
        }
      }
      const search = debounce(() => {
        // console.log(record);
        const address = getFieldsValue().address;
        addressSearch(address);
      }, 300);
      // 详情地址选择
      function addressChange(record: any) {
        areaOptions.value = [];
        addressOptions.value = [];
        setFieldsValue({ address: record });
        // cityOptions.value = [];
        getAreaSiteApi({ address: record }).then((res: any) => {
          const { data } = res;
          setAreaOptions(data.area1, cityOptions.value, 'city', 'id');
          setAreaOptions(data.area2, areaOptions.value, 'area', 'area');
        });
      }
      // 处理地址格式
      function setAreaOptions(data: any, options: Ioptions[], area: string, value: string) {
        if (Array.isArray(data)) {
          data.map((item) => {
            const ele: Ioptions = {
              key: item.id,
              label: item[area],
              value: item[value] + '',
            };
            options.push(ele);
          });
          if (area == 'area' && !getFieldsValue().area) {
            let tmp: any[] = data.filter((item) => item.isShow === 1);
            if (tmp.length) {
              //值为1
              if (tmp[0].isShow == 1) {
                setFieldsValue({ area: tmp[0][value] });
              }
            } else {
              //全部为0
              const ele: Ioptions = {
                key: '其他',
                label: '其他',
                value: '其他',
              };
              options.push(ele);
              setFieldsValue({ area: '其他' });
            }
          }
        } else if (data instanceof Object) {
          const ele: Ioptions = {
            key: data['id'],
            label: data[area],
            value: data[value] + '',
          };
          const flag: Boolean = unref(options).some((item) => {
            return item.value == ele.value;
          });
          if (!flag) {
            options.push(ele);
          }
          if (area == 'city' && !getFieldsValue().area) {
            setFieldsValue({ [area]: data['id'] });
          }
        } else {
          const ele: Ioptions = {
            key: data,
            label: data,
            value: data + '',
          };
          options.push(ele);
          setFieldsValue({ area: data });
        }
      }
      async function onSubmit() {
        const times: Time[] = [];
        // let flag: Boolean = true;
        businessList.value.map((item: Time) => {
          // if (!item.startWeeks && !item.endWeeks && item.startTime && item.endTime) {
          //   return (flag = false);
          // }
          // times.push(
          //   `${item.startWeeks}-${item.endWeeks} ${moment(item.startTime).format('LT')}-${moment(
          //     item.endTime
          //   ).format('LT')}`
          // );
          if (item.children && item.children.length > 0) {
            let children: ChildrenTime[] = [];
            item.children.map((ele: ChildrenTime) => {
              children.push({
                startTime: moment(ele.startTime).format('LT'),
                endTime: moment(ele.endTime).format('LT'),
              });
            });
            times.push({
              day: item.day,
              children: children,
            });
          }
        });
        setFieldsValue({ doBusinessTime: JSON.stringify(times) });
        // if (!flag) {
        //   return createMessage.error('请填完整营业时间！');
        // }
        const values = await validate();
        // values.doBusinessTime = times.join(',');
        // if (!values.doBusinessTime) {
        //   return createMessage.error('请选择营业时间！');
        // }
        for (const key in values) {
          let element: any = values[key];
          if (!element) {
            if (key == 'videoUrlsList') {
              element = [];
            } else {
              element = '';
            }
          }
        }
        if (!values.videoUrlsList) {
          values.videoUrlsList = [];
        }
        values.province = getCityChinese(values.city);
        if (unref(id)) {
          values.id = unref(id);
          EditApi(values).then((res: any) => {
            if (res.code == 200) {
              resetForm('edit');
            }
          });
        } else {
          AddApi(values).then((res: any) => {
            if (res.code == 200) {
              resetForm('new');
            }
          });
        }
      }
      function getCityChinese(record: number | string) {
        let city = '';
        cityOptions.value.map((item: any) => {
          if (item.value == record) {
            city = item.label;
          }
        });
        return city;
      }
      function goBack() {
        router.push({
          path: '/merchantAdmin',
        });
      }

      const sub = throttle(onSubmit);
      function resetForm(type: string) {
        createMessage.success(type == 'new' ? '新增商家成功！' : '编辑商家成功！');
        resetFields();
        businessList.value = cloneDeep(times);
        if (unref(id)) {
          editData(unref(id));
        }
      }
      const handleChange = (info: FileInfo) => {
        if (info.file.status === 'uploading') {
          return;
        }
        if (info.file.status === 'done') {
          const { code, data } = info.file.response;
          if (code == 200) {
            setFieldsValue({ coverUrl: data[0] });
          }
        }
        if (info.file.status === 'error') {
          createMessage.error('上传失败！');
        }
        spinning.value = false;
      };
      const beforeUpload = (file: FileItem) => {
        spinning.value = true;
        const isJpgOrPng =
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/JPG' ||
          file.type === 'image/JEPG';
        if (!isJpgOrPng) {
          createMessage.error('上传图形格式只能上传：JPG、PNG、JPEG、JEPG!');
        }
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isLt2M) {
          createMessage.error('图像必须小于5MB!');
        }
        return isJpgOrPng && isLt2M;
      };
      return {
        registerForm,
        ListApi,
        weeksOptions,
        moment,
        search,
        addressChange,
        addressOptions,
        areaOptions,
        cityOptions,
        businessList,
        addBusinessTime,
        goBack,
        deleteTime,
        sub,
        cityChange,
        uploadImgApi,
        handleChange,
        beforeUpload,
        fileList,
        spinning,
        areaSearchBlur,
      };
    },
  });
</script>

<style lang="less" scoped>
  .ant-spin-nested-loading {
    width: 104px;
  }
  :deep(.ant-upload) {
    margin: 0;
  }
  :deep(.vben-page-wrapper-content) {
    padding: 30px 15px;
  }
  .weeks-box {
    position: relative;
    .weeks-box-one {
      display: inline-block;
      width: 100%;
      margin-top: 5px;
    }
    .business-box-item {
      display: flex;
      justify-content: flex-start;
      .weeks-item {
        span {
          margin: 0 5px;
        }
        .ant-btn {
          margin-left: 10px;
        }
      }
      .time-item {
        margin: 0 10px;
        .ant-btn {
          margin-left: 10px;
        }
      }
    }
  }
  :deep(.ant-row) {
    .ant-col {
      &:nth-child(6),
      &:nth-child(5) {
        .ant-form-item-control-wrapper {
          flex: 1;
          max-width: calc(100% - 130px);
        }
        // .ant-form-item-control {
        //   max-width: ;
        // }
      }
    }
  }
  :deep(.hint) {
    color: red;
  }
  .address-list {
    position: relative;
    ul {
      width: 100%;
      position: absolute;
      top: 40px;
      left: 0;
      max-height: 300px;
      overflow-y: scroll;
      background: #fff;
      z-index: 99;
      li {
        padding-left: 5px;
        cursor: pointer;
        &:hover {
          background: #f5f5f5;
        }
      }
    }
  }
</style>
